<?php
/**
 * JoiVideo - video gallery component for Joostina
 *
 * Backend controller
 *
 * @version 0.1
 * @package JoiVideo
 * @subpackage	Admin
 * @author JoostinaTeam
 * @copyright (C) 2007-2010 Joostina Team
 * @license see license.txt
 *
 **/

defined('_VALID_MOS') or die();

require_once ($mainframe->getPath('class'));

$task = mosGetParam($_REQUEST, 'task');
$act = mosGetParam($_REQUEST, 'act');
$cid = mosGetParam($_REQUEST, 'cid', array(0));

if (!is_array($cid)) {
    $cid = array($cid);
}

switch ($act) {
    case 'categories':
	_categories($task, $cid);
	break;
    case 'video':
	_videos($task, $cid);
	break;
    case 'configuration':
	_configuration($task, $cid);
	break;
    case 'plugins':
	_plugins($task, $cid);
	break;
    case 'extrafields':
	_extrafields($task, $cid);
	break;
    default:
	include_once (_JOI_GALLERY_ADMIN . DS . 'view' . DS . 'credits.php');
	break;
}

function _videos($task, $cid) {
    global $option;

    switch ($task) {
	case 'new':
	    add_video();
	    break;
	case 'edit':
	    edit_video($cid[0]);
	    break;
	case 'apply':
	case 'save':
	    save_video();
	    break;
	case 'remove':
	    remove_video($cid);
	    break;
	case 'cancel':
	    mosRedirect('index2.php?option=' . $option . '&act=videos');
	    break;
	case 'orderup':
	    reorder_video($cid[0], - 1);
	    break;
	case 'orderdown':
	    reorder_video($cid[0], 1);
	    break;
	case 'saveorder':
	    saveOrder_videos($cid);
	    break;
	case 'publish':
	    setState_video($cid, 1);
	    break;
	case 'unpublish':
	    setState_video($cid, 0);
	    break;
	case 'upload':
	    _process_upload();
	    break;
	default:
	    show_videos();
	    break;
    }
}

function _categories($task, $cid) {
    global $option;

    switch ($task) {
	case 'new':
	    edit_category(0);
	    break;
	case 'edit':
	    edit_category($cid[0]);
	    break;
	case 'apply':
	case 'save':
	    save_category();
	    break;
	case 'remove':
	    remove_category($cid);
	    break;
	case 'cancel':
	    mosRedirect('index2.php?option=' . $option . '&act=categories');
	    break;
	case 'orderup':
	    reorder_category($cid[0], - 1);
	    break;
	case 'orderdown':
	    reorder_category($cid[0], 1);
	    break;
	case 'saveorder':
	    saveOrder_category($cid);
	    break;
	case 'publish':
	    setState_category($cid[0], 1);
	    break;
	case 'unpublish':
	    setState_category($cid[0], 0);
	    break;
	default:
	    show_categories();
	    break;
    }
}

function _configuration($task, $cid) {
    global $option;

    switch ($task) {
	case 'save':
	case 'apply':
	    save_config($option, $task);
	    break;
	case 'cancel':
	    mosRedirect('index2.php?option=' . $option . '&act=configuration');
	    break;
	case 'new':
	    config($option, 1);
	    break;
	case 'config':
	    config($option);
	    break;
	case 'remove':
	    remove_config($cid, $option);
	    break;
	default:
	    config_list($option);
	    break;
    }
}

function _plugins($task, $cid) {
    global $option;

    switch ($task) {
	case 'save':
	case 'apply':
	    save_plugin($option, $task);
	    break;
	case 'cancel':
	    mosRedirect('index2.php?option=' . $option . '&act=plugins');
	    break;
	case 'plugin':
	    plugin($option);
	    break;
	case 'remove':
	    remove_plugin($cid, $option);
	    break;
	default:
	    plugins_list($option);
	    break;
    }
}

function _extrafields($task, $cid) {
    global $option;

    switch ($task) {

	case 'save':
	case 'apply':
	    save_extrafield($option, $task);
	    break;
	case 'cancel':
	    mosRedirect('index2.php?option=' . $option . '&act=extrafields');
	    break;
	case 'new':
	    extrafield($option, 0);
	    break;
	case 'extrafield':
	    extrafield($option, $cid[0]);
	    break;
	case 'remove':
	    remove_extrafield($cid, $option);
	    break;
	case 'publish':
	    setState_extrafield($cid[0], 1);
	    break;
	case 'unpublish':
	    setState_extrafield($cid[0], 0);
	    break;
	default:
	    extrafields_list($option);
	    break;
    }
}

function extrafields_list($option) {
    $mainframe = & mosMainFrame::getInstance();
    $extra_fields = new joiExtraFields($mainframe, 'com_joivideo');
    $extra_fields->load_fields();
    $extrafields_list = $extra_fields->_loaded_fields;
    include_once($mainframe->getCfg('absolute_path') . DS . 'administrator' . DS . 'components' . DS . $option . DS . 'view' . DS . 'extrafields_list.php');
}

function extrafield($option, $id) {
    $mainframe = & mosMainFrame::getInstance();
    $field = new joiExtraFields($mainframe, 'com_joivideo');
    $field->load($id);
    include_once($mainframe->getCfg('absolute_path') . DS . 'administrator' . DS . 'components' . DS . $option . DS . 'view' . DS . 'extrafield.php');
}

function save_extrafield($option, $task) {
    $mainframe = & mosMainFrame::getInstance();

    $field = new joiExtraFields($mainframe, 'com_joivideo');
    $field->bind($_POST);
    $field->published = intval(mosGetParam($_REQUEST, 'published', 0));

    if (!$field->id && !$field->check()) {
	echo "<script> alert('" . $field->getError() . "'); window.history.go(-1); </script>\n";
	exit();
    }
    if (!$field->store()) {
	echo "<script> alert('" . $field->getError() . "'); window.history.go(-1); </script>\n";
	exit();
    }

    switch ($task) {
	case 'save':
	    mosRedirect('index2.php?option=' . $option . '&act=extrafields', 'Configuration saved');
	    break;
	case 'apply':
	    mosRedirect('index2.php?option=' . $option . '&act=extrafields&task=field&cid=' . $field->id, 'Configuration saved');
	    break;
    }
}

function setState_extrafield($ids, $published) {
    global $database, $option;

    $mainframe = & mosMainFrame::getInstance();

    $row = new joiExtraFields($mainframe, 'com_joivideo');
    for ($i = 0, $n = count($ids); $i < $n; $i++) {

	$row->load($ids[$i]);

	$row->published = $published;

	if (!$row->store()) {
	    echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
	    exit();
	}
    }

    mosRedirect('index2.php?option=' . $option . '&act=extrafields');
}

function remove_extrafield($cid, $option) {
    global $database;
    $mainframe = & mosMainFrame::getInstance();

    //for($i = 0,$n = count ($ids); $i < $n; $i ++){
    //echo $ids[$i];
    //joiExtraFields::delete_field($ids[$i]);
    //}

    $row = new joiExtraFields($mainframe, 'com_joivideo');

    for ($i = 0, $n = count($cid); $i < $n; $i++) {
	$id = $cid[$i];
	$row->delete($id);
	$row->delete_values($id);
    }

    mosRedirect('index2.php?option=' . $option . '&act=extrafields', 'Removed');
}

function plugins_list($option) {
    $mainframe = & mosMainFrame::getInstance();
    $plugins = new joiGalleryPlugins($mainframe);
    $plugins_list = $plugins->get_plugins_list();
    $plugins_array = $plugins->config->_all_configs;

    $limit = intval(mosGetParam($_REQUEST, 'limit', 0));
    $limitstart = intval(mosGetParam($_REQUEST, 'limitstart', 0));
    require_once($mainframe->getCfg('absolute_path') . '/administrator/includes/pageNavigation.php');
    $pageNav = new mosPageNav(count($plugins_list), $limitstart, $limit);


    include_once($mainframe->getCfg('absolute_path') . DS . 'administrator' . DS . 'components' . DS . $option . DS . 'view' . DS . 'plugins_list.php');
}

function plugin($option) {
    $mainframe = & mosMainFrame::getInstance();
    $database = & database::getInstance();

    $plug = mosGetParam($_REQUEST, 'plugin', '');
    $type = mosGetParam($_REQUEST, 'type', '');

    $plugin = new joiPlugins($database, 'joigallery', $plug, $type);
    $plugin->config->display_config($option);
}

function save_plugin($option, $task) {
    $database = & database::getInstance();

    $plug = mosGetParam($_REQUEST, 'plugin', '');
    $type = mosGetParam($_REQUEST, 'type', '');

    $plugin = new joiPlugins($database, 'joigallery', $plug, $type);
    $plugin->config->save_config($option);

    switch ($task) {
	case 'save':
	    mosRedirect('index2.php?option=' . $option . '&act=plugins', 'Configuration saved');
	    break;
	case 'apply':
	    mosRedirect('index2.php?option=' . $option . '&act=plugins&plugin=' . $plug, 'Configuration saved');
	    break;
    }
}

function config_list($option) {
    $mainframe = & mosMainFrame::getInstance();
    $configs = joiGalleryConfig::get_configs_list();

    $limit = intval(mosGetParam($_REQUEST, 'limit', 0));
    $limitstart = intval(mosGetParam($_REQUEST, 'limitstart', 0));
    require_once($mainframe->getCfg('absolute_path') . '/administrator/includes/pageNavigation.php');
    $pageNav = new mosPageNav(count($configs), $limitstart, $limit);

    include_once($mainframe->getCfg('absolute_path') . DS . 'administrator' . DS . 'components' . DS . $option . DS . 'view' . DS . 'config_list.php');
}

function config($option, $isNew = 0) {
    $mainframe = & mosMainFrame::getInstance();
    $database = & database::getInstance();
    $group = mosGetParam($_REQUEST, 'group', 'default');

    $config = new joiGalleryConfig($database, 'joigallery', $group);
    $config->display_config($option, $isNew);
}

function save_config($option, $task) {
    $database = & database::getInstance();
    $group = mosGetParam($_REQUEST, 'group', 'default');

    $config = new joiGalleryConfig($database, 'joigallery', $group);
    $config->save_config();

    switch ($task) {
	case 'save':
	    mosRedirect('index2.php?option=' . $option . '&act=configuration', 'Configuration saved');
	    break;
	case 'apply':
	    mosRedirect('index2.php?option=' . $option . '&act=configuration&task=config&group=' . $group, 'Configuration saved');
	    break;
    }
}

function remove_config($ids, $option) {

    for ($i = 0, $n = count($ids); $i < $n; $i ++) {
	echo $ids[$i];
	joiGalleryConfig::delete_config($ids[$i]);
    }

    mosRedirect('index2.php?option=' . $option . '&act=configuration', 'Removed');
}

function show_categories() {
    global $database, $mainframe, $option;

    $limit = intval($mainframe->getUserStateFromRequest("viewlistlimit", 'limit', $mainframe->getCfg('list_limit')));
    $limitstart = intval($mainframe->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0));
    $cid = intval($mainframe->getUserStateFromRequest("view{$option}cid", 'cid', 0));
    $search = $mainframe->getUserStateFromRequest("search{$option}", 'search', '');
    $search = $database->getEscaped(trim(strtolower($search)));

    $cat = new joiGalleryCategory($database);

    //Получаем список всех категорий
    $rows = $cat->get_categories_admin($cid, $search);

    //Пересортировываем категории с учетом отношений родитель/потомок
    $category_tree = $cat->generate_tree($rows);

    //Подсчет количества категорий
    $total = count($category_tree);

    //Подключение класса пагинацияя
    require_once ($mainframe->getCfg('absolute_path') . '/administrator/includes/pageNavigation.php');
    $pageNav = new mosPageNav($total, $limitstart, $limit);

    //Разбиваем категории по страницам
    $rows = array_slice($category_tree, $pageNav->limitstart, $pageNav->limit);

    $categories = joiGalleryCategory::getCategorieTree();
    $obj = new stdClass();
    $obj->id = 0;
    $obj->name = ' - all - ';
    array_unshift($categories, $obj);

    $lists = array();
    $lists['search'] = $search;
    $lists['cid'] = mosHTML::selectList($categories, 'cid', 'onchange="document.adminForm.submit();"', 'id', 'name', $cid);

    include_once (_JOI_GALLERY_ADMIN . DS . 'view' . DS . 'category_list.php');
}

function edit_category($id) {
    global $database, $my, $option;

    $row = new mosCategory($database);
    $row->load($id);

    if (!$row->id) {
	$row->published = 1;
    }

    $categories = joiGalleryCategory::getCategorieTree();

    $obj = new stdClass();
    $obj->id = 0;
    $obj->name = 'Top';

    array_unshift($categories, $obj);

    $lists = array();
    $lists['parent_id'] = mosHTML::selectList($categories, 'parent_id', 'class="inputbox" size="1"', 'id', 'name', $row->parent_id);
    $lists['published'] = mosHTML::yesnoRadioList('published', '', intval($row->published));

    include_once (_JOI_GALLERY_ADMIN . DS . 'view' . DS . 'edit_category.php');
}

function save_category() {
    global $database, $task, $option, $my;

    $row = new mosCategory($database);
    $row->bind($_POST);

    if (!$row->id) {
	$row->ordering = 999999999;
    }

    // avoid linking category to itself
    if ($row->parent_id == $row->id) {
	$row->parent_id = 0;
    }

    $row->section = 'com_joivideo';

    $row->published = intval(mosGetParam($_REQUEST, 'published', 0));

    if (!$row->check()) {
	echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
	exit();
    }
    if (!$row->store()) {
	echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
	exit();
    }

    $row->updateOrder('section = \'com_joivideo\'');

    switch ($task) {
	case 'save':
	    mosRedirect('index2.php?option=' . $option . '&act=categories', 'Changes to category saved');
	    break;
	case 'apply':
	    mosRedirect('index2.php?option=' . $option . '&act=categories&task=edit&cid=' . $row->id . '&hidemainmenu=1',
		    'Changes to category saved');
	    break;
    }
}

function remove_category($cid) {
    global $database, $option;

    $row = new mosCategory($database);
    $videos = new joiGalleryvideo($database);

    for ($i = 0, $n = count($cid); $i < $n; $i++) {
	$id = $cid[$i];

	//check for videos
	$total = $videos->check_videos_by_cat($id);

	if ($total > 0) {
	    echo "<script> alert('" . addslashes(_C_JOIGALLERY_CAT_DELETE_STILL_videos) . "'); window.history.go(-1); </script>\n";
	    exit();
	}

	//check for subcategories
	$total = $videos->check_subcats_by_cat($id);

	if ($total > 0) {
	    echo "<script> alert('" . addslashes(_C_JOIGALLERY_CAT_DELETE_STILL_SUBCATS) . "'); window.history.go(-1); </script>\n";
	    exit();
	}

	$row->delete($id);
    }

    mosRedirect('index2.php?option=' . $option . '&act=categories', 'Selected categories removed');
}

function saveOrder_category($cid) {
    global $database, $option;

    $order = mosGetParam($_POST, 'order', array(0));
    $row = new mosCategory($database);
    $conditions = array();

    for ($i = 0, $n = count($cid); $i < $n; $i++) {
	$row->load($cid[$i]);

	if ($row->ordering != $order[$i]) {
	    $row->ordering = $order[$i];

	    if (!$row->store()) {
		echo "<script> alert('" . $database->getErrorMsg() . "'); window.history.go(-1); </script>\n";
		exit();
	    }

	    $condition = "section = 'com_joivideo'";
	    $found = false;

	    for ($j = 0, $k = count($conditions); $j < $k; $j++) {
		$cond = $conditions[$j];

		if ($cond[1] == $condition) {
		    $found = true;
		    break;
		}
	    }
	    if (!$found) {
		$conditions[] = array($row->id, $condition);
	    }
	}
    }

    for ($i = 0, $n = count($conditions); $i < $n; $i++) {
	$condition = $conditions[$i];

	$row->load($condition[0]);
	$row->updateOrder($condition[1]);
    }

    mosRedirect('index2.php?option=' . $option . '&act=categories');
}

function reorder_category($id, $direction) {
    global $database, $option;

    $row = new mosCategory($database);
    $row->load($id);

    $row->move($direction, 'section = \'com_joivideo\'');

    mosRedirect('index2.php?option=' . $option . '&act=categories');
}

function setState_category($id, $published) {
    global $database, $option;

    $row = new mosCategory($database);
    $row->load($id);
    $row->published = $published;

    if (!$row->store()) {
	echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
	exit();
    }

    mosRedirect('index2.php?option=' . $option . '&act=categories');
}

function _process_upload() {
    global $option;

    $return = processImage::upload_handler();

    if ($return == 1) {
	$msg = 'video added successfully';
    }
    else {
	$msg = $return . ' images added successfully';
    }
    mosRedirect('index2.php?option=' . $option . '&act=videos&task=new', $msg);
}

function show_videos() {
    global $database, $mainframe, $option;

    $limit = intval($mainframe->getUserStateFromRequest("viewlistlimit", 'limit', $mainframe->getCfg('list_limit')));
    $limitstart = intval($mainframe->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0));
    $cid = intval($mainframe->getUserStateFromRequest("view{$option}cid", 'cid', 0));

    $videos = new joiGalleryvideo($database);
    $total = $videos->get_count_videos_admin($cid);

    require_once ($mainframe->getCfg('absolute_path') . '/administrator/includes/pageNavigation.php');
    $pageNav = new mosPageNav($total, $limitstart, $limit);

    $rows = $videos->load_videos_admin($cid, $limitstart, $limit);

    $categories = joiGalleryCategory::getCategorieTree();
    $obj = new stdClass();
    $obj->id = 0;
    $obj->name = ' - all - ';
    array_unshift($categories, $obj);

    $lists = array();
    $lists['cid'] = mosHTML::selectList($categories, 'cid', 'onchange="document.adminForm.submit();"', 'id', 'name', $cid);

    include_once (_JOI_GALLERY_ADMIN . DS . 'view' . DS . 'videos.php');
}

function add_video() {
    global $database, $option, $mainframe;

    $lists = array();
    $categories = joiGalleryCategory::getCategorieTree();
    $lists['cid'] = mosHTML::selectList($categories, 'cid', 'class="inputbox text_area"', 'id', 'name');

    $options = array(mosHTML::makeOption('name', 'Sort by name - A-Z'), mosHTML::makeOption('rname', 'Sort by name - Z-A'), mosHTML::makeOption
		('c_date', 'Sort by created date'), mosHTML::makeOption('m_date', 'Sort by modified date'));
    $lists['sort'] = mosHTML::selectList($options, 'sort', 'class="inputbox text_area"', 'value', 'text', 'name');

    include_once (_JOI_GALLERY_ADMIN . DS . 'view' . DS . 'video_add.php');
}

function edit_video($id) {
    global $database, $option, $mainframe;

    $row = new joiGalleryvideo($database);
    $row->load($id);

    $config = new joiGalleryConfig($database);

    $categories = joiGalleryCategory::getCategorieTree();
    $obj = new stdClass();
    $obj->id = 0;
    $obj->name = ' - select - ';
    array_unshift($categories, $obj);

    $lists = array();
    $lists['cid'] = mosHTML::selectList($categories, 'cid', '', 'id', 'name', $row->cid);

    include_once (_JOI_GALLERY_ADMIN . DS . 'view' . DS . 'video_edit.php');
}

function save_video() {
    global $option, $database, $task;

    $row = new joiGalleryvideo($database);
    $row->bind($_POST);

    $row->default = intval(mosGetParam($_REQUEST, 'default', 0));

    if ($row->default) {
	$row->clean_default($row->cid);
    }

    if (!$row->id) {
	$row->ordering = 999999999;
    }

    if (!$row->check()) {
	echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
	exit();
    }
    if (!$row->store()) {
	echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
	exit();
    }

    $row->updateOrder('cid = ' . (int) $row->cid);

    switch ($task) {
	case 'save':
	    mosRedirect('index2.php?option=' . $option . '&act=videos', 'Changes to video saved');
	    break;
	case 'apply':
	    mosRedirect('index2.php?option=' . $option . '&act=videos&task=edit&cid=' . $row->id . '&hidemainmenu=1', 'Changes to video saved');
	    break;
    }
}

function remove_video($ids) {
    global $database, $option, $mainframe;

    $row = new joiGalleryvideo($database);
    $config = new joiGalleryConfig($database);

    for ($i = 0, $n = count($ids); $i < $n; $i++) {
	$id = intval($ids[$i]);

	$row->load($id);
	$row->remove_images($row, $config);
	$row->delete();
	$row->updateOrder('cid = ' . $row->cid);
    }

    mosRedirect('index2.php?option=' . $option . '&act=videos', 'Selected items have been removed');
}

function setState_video($ids, $state) {
    global $database, $option;

    $row = new joiGalleryvideo($database);

    for ($i = 0, $n = count($ids); $i < $n; $i++) {

	$row->load($ids[$i]);

	$row->state = $state;

	if (!$row->store()) {
	    echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
	    exit();
	}
    }

    mosRedirect('index2.php?option=' . $option . '&act=videos');
}

function reorder_video($id, $direction) {
    global $database, $option;

    $row = new joiGalleryvideo($database);
    $row->load($id);

    $row->move($direction, 'cid = ' . (int) $row->cid);

    mosRedirect('index2.php?option=' . $option . '&act=videos');
}

function saveOrder_videos($cid) {
    global $database, $option;

    $order = mosGetParam($_POST, 'order', array(0));
    $row = new joiGalleryvideo($database);
    $conditions = array();

    for ($i = 0, $n = count($cid); $i < $n; $i++) {
	$row->load($cid[$i]);

	if ($row->ordering != $order[$i]) {
	    $row->ordering = $order[$i];

	    if (!$row->store()) {
		echo "<script> alert('" . $database->getErrorMsg() . "'); window.history.go(-1); </script>\n";
		exit();
	    }

	    $condition = 'cid = ' . (int) $row->cid;
	    $found = false;

	    for ($j = 0, $k = count($conditions); $j < $k; $j++) {
		$cond = $conditions[$j];

		if ($cond[1] == $condition) {
		    $found = true;
		    break;
		}
	    }
	    if (!$found) {
		$conditions[] = array($row->id, $condition);
	    }
	}
    }

    for ($i = 0, $n = count($conditions); $i < $n; $i++) {
	$condition = $conditions[$i];

	$row->load($condition[0]);
	$row->updateOrder($condition[1]);
    }

    mosRedirect('index2.php?option=' . $option . '&act=videos');
}
